#pragma once
#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cstring>
#include<unistd.h>

enum s
{
    SocketErr = 2,
    BindErr,
    ListenErr,
};

const int backlog = 10;

class Sock
{
public:
    Sock()
    {}

    void Socket()
    {
        listensocketfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (listensocketfd_ < 0)
        {
            std::cout << "socket failed" << "error: " << errno << "strerrno: " << strerror(errno);
            exit(SocketErr);
        }
        int opt = 1;
        setsockopt(listensocketfd_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    }

    void Bind(const uint16_t& port)
    {
        struct sockaddr_in local;
        memset(&(local), 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        socklen_t len = sizeof(local);
        if (bind(listensocketfd_, (const sockaddr*)&local, len) < 0)
        {
            std::cout << "bind fail" << std::endl;
            exit(BindErr);
        }
    }

    void Listen()
    {
        if (listen(listensocketfd_, backlog) < 0)
        {
            std::cout << "listen failed" << std::endl;
            exit(ListenErr);
        }
    }

    int Accept(std::string* clientip, uint16_t* clientport)
    {
        struct sockaddr_in client;
        memset(&client, 0, sizeof(client));
        socklen_t len = sizeof(client);
        int socketfd = accept(listensocketfd_, (sockaddr*)&client, &len);
        if (socketfd < 0)
        {
            std::cout << "accept failed" << std::endl;
        }
        char str[64];
        inet_ntop(AF_INET, &client.sin_addr, str, sizeof(str));

        *clientip = str;
        *clientport = ntohs(client.sin_port);
        return socketfd;
    }

    void Connect()
    {

    }

    void Close()
    {
        close(listensocketfd_);
    }

    int get()
    {
        return listensocketfd_;
    }

private:
    int listensocketfd_;
};
